package com.odriver.neulearn;

import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.odriver.neulearn.Activity.MeunActivity;
import com.odriver.neulearn.Bean.LoginBean;
import com.odriver.neulearn.Bean.MenuBean;
import com.odriver.neulearn.Util.SaveUtil;
import com.odriver.neulearn.Util.ScreenUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * A login screen that offers login via email/password.
 */
public class LoginActivity extends AppCompatActivity implements OnClickListener {
    private RequestQueue mQueue;
    private ImageView imageView;
    private Button button;
    private EditText userName, userPassword, userCode;
    private TextView changeCode;
    private LoginBean loginBean;
    public String LOGIN_URL = "http://www.neuedu.cn/m/mobileLogin!loginNeu.action";
    public String PIC_URL = "http://www.neuedu.cn/imgcode";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ScreenUtil.setScreenNoTitle(this);
        setContentView(R.layout.activity_login);
        imageView = (ImageView) findViewById(R.id.idp_login_pic);
        initView();
    }

    public void initView() {
        initCode();
        button = (Button) findViewById(R.id.idp_login_button);
        userName = (EditText) findViewById(R.id.idp_login_username);
        userPassword = (EditText) findViewById(R.id.idp_login_password);
        userCode = (EditText) findViewById(R.id.idp_login_code);
        changeCode = (TextView) findViewById(R.id.idp_login_change);

        button.setOnClickListener(this);
        changeCode.setOnClickListener(this);
    }

    public void initCode() {
        mQueue = Volley.newRequestQueue(this);
        ImageRequest imageRequest = new ImageRequest(
                PIC_URL,
                new Response.Listener<Bitmap>() {
                    @Override
                    public void onResponse(Bitmap response) {
                        imageView.setImageBitmap(response);
                    }

                }, 1000, 500, Bitmap.Config.RGB_565, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                imageView.setImageResource(R.mipmap.ic_launcher);
            }
        }) {
            @Override
            protected Response<Bitmap> parseNetworkResponse(NetworkResponse response) {
                Map<String, String> responseHeaders = response.headers;
                String rawCookies = responseHeaders.get("Set-Cookie");//cookie值
                SaveUtil.saveCookieInSharePreference(LoginActivity.this,rawCookies);
                return super.parseNetworkResponse(response);
            }
        };
        mQueue.add(imageRequest);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.idp_login_button: {
                if(checkEdit())
                {
                    Login();
                }
                break;
            }
            case R.id.idp_login_change: {
                initCode();
                break;
            }
        }
    }

    private void Login(){
        StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
                new Response.Listener() {
                    @Override
                    public void onResponse(Object response) {
                        Log.d("网络消息", response.toString());
                        Gson gson = new Gson();
                        loginBean = gson.fromJson((String) response, LoginBean.class);
                        if (loginBean.getLoginReturn().getLoginFlag().equals("1")){
                            startActivity(new Intent(LoginActivity.this, MeunActivity.class));
                            finish();
                        }else {
                            Toast.makeText(LoginActivity.this,loginBean.getLoginReturn().getMsg(),Toast.LENGTH_SHORT).show();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        initCode();
                        Toast.makeText(LoginActivity.this,"登录失败，请检查用户名密码",Toast.LENGTH_SHORT).show();
                        Log.e("网络消息", error.getMessage(), error);
                    }
                }
        ) {
            @Override//用户名：15074714@qq.com  密码：123456
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
//                map.put("username", "15074714@qq.com");
//                map.put("pwd", "123456");
                map.put("username", userName.getText().toString());
                map.put("pwd", userPassword.getText().toString());
                map.put("imgcode", userCode.getText().toString());
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("Cookie",SaveUtil.getCookie(LoginActivity.this));
                Log.d("网络消息：",map.get("Cookie"));
                return map;
            }
        };

        mQueue.add(stringRequest);
    }

    private boolean checkEdit(){
        if(userName.getText().toString().trim().equals("")){
            Toast.makeText(LoginActivity.this, "用户名不能为空", Toast.LENGTH_SHORT).show();
        }else if(userPassword.getText().toString().trim().equals("")){
            Toast.makeText(LoginActivity.this, "密码不能为空", Toast.LENGTH_SHORT).show();
        }else{
            return true;
        }
        return false;
    }

}

